<template>
  <div>
    <div style="display: flex;gap: 10px">
      <div class="card-container">
        <div class="card" id="bar2" style="flex: 1;height:400px;"></div>
        <div v-if="!data.hasBar2Data" class="no-data-overlay" id="bar2-no-data">
          <div class="no-data-icon">🎓</div>
          <h3>暂无学分数据</h3>
          <p>当前没有学分统计信息，请导入学分数据或设置学分规则</p>
        </div>
      </div>
      <div class="card-container">
        <div class="card" id="line" style="flex: 1;height:400px;margin-right: 10px;"></div>
        <div v-if="!data.hasLineData" class="no-data-overlay" id="line-no-data">
          <div class="no-data-icon">📈</div>
          <h3>暂无活跃数据</h3>
          <p>近两周没有学生活跃记录，请检查系统或开展学生活动</p>
        </div>
      </div>
    </div>
    <div style="display: flex;gap: 10px;margin-top: 5px">
      <div class="card-container">
        <div class="card" id="pie" style="flex: 1;height:400px;"></div>
        <div v-if="!data.hasPieData" class="no-data-overlay" id="pie-no-data">
          <div class="no-data-icon">📝</div>
          <h3>暂无提交数据</h3>
          <p>学生尚未提交任何材料，请布置任务或开启材料提交功能</p>
        </div>
      </div>
      <div class="card-container">
        <div class="card" id="bar" style="flex: 1;height:400px;margin-right: 10px;"></div>
        <div v-if="!data.hasBarData" class="no-data-overlay" id="bar-no-data">
          <div class="no-data-icon">📊</div>
          <h3>暂无专业数据</h3>
          <p>当前学院还没有专业注册数据，请添加专业或导入学生信息</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {reactive, onMounted, ref, onUnmounted} from "vue";
import * as echarts from 'echarts';
import { ElMessage } from "element-plus";
import alovaInstance from "@/utils/request.js";

const data = reactive({
  user: JSON.parse(localStorage.getItem('credit-system-user') || '{}'),
  chartInstances: {},
  // 无数据标志位
  hasBarData: false,
  hasLineData: false,
  hasPieData: false,
  hasBar2Data: false
});

// 图表配置（完整保留原代码）
const barOption = {
  title: {
    text: '本院各专业注册学生人数统计',
  },
  tooltip: {},
  legend: {
    data: ['注册人数', '注册趋势']
  },
  xAxis: {
    data: [],
    axisLabel: {
      showMaxLabel: true, // 显示首尾标签
      interval: 0, // 强制显示所有标签，默认会间隔隐藏
      rotate: 45, // 文字旋转 45 度，避免横向挤压
      margin: 5 // 标签与轴线的间距
    }
  },
  yAxis: {},
  series: [
    {
      name: '注册人数',
      type: 'bar',
      data: [],
      itemStyle: {
        color: function (params) {
          //自定义颜色
          let colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
          return colorList[(params.dataIndex % colorList.length)]
        }
      }
    },
    {
      name: '注册趋势',
      type: 'line',
      data: [], // 后续会与柱状图数据同步
      yAxisIndex: 0, // 与柱状图共用Y轴
      symbol: 'circle', // 显示数据点
      symbolSize: 8, // 数据点大小
      lineStyle: {
        width: 2, // 线宽
        color: '#a05416' // 折线颜色
      },
      itemStyle: {
        color: '#6b0e07' // 数据点颜色
      }
    }
  ]
}

const lineOption = {
  title: {
    text: '近两周本院学生活跃账号数量统计',
  },
  tooltip: {},
  legend: {
    data: ['每日账号活跃数量']
  },
  xAxis: {
    data: [],
    axisLabel: {
      showMaxLabel: true, // 显示首尾标签
      interval: 0, // 强制显示所有标签，默认会间隔隐藏
      rotate: 45, // 文字旋转 45 度，避免横向挤压
      margin: 10 // 标签与轴线的间距
    }
  },
  yAxis: {},
  series: [
    {
      name: '每日账号活跃数量',
      type: 'line',
      smooth: true,
      data: [],
      itemStyle: {
        color: function (params) {
          //自定义颜色
          let colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'];
          return colorList[(params.dataIndex % colorList.length)]
        }
      }
    },
  ]
}

const pieOption = {
  title: {
    text: '本院各专业学生提交材料数量比例图',
    subtext: '饼状图',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '学生提交材料数量',
      type: 'pie',
      radius: '50%',
      data: [],
      /*center: ['50%', '55%'],*/
      label: {
        formatter: '{b}: {@2012} ({d}%)'
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
}

const barOption4 = {
  title: {
    text: '各专业学生学分合格统计',
  },
  tooltip: {},
  legend: {
    data: ['合格人数', '不合格人数', '专业总人数']
  },
  xAxis: {
    data: [],
    axisLabel: {
      showMaxLabel: true, // 显示首尾标签
      interval: 0, // 强制显示所有标签，默认会间隔隐藏
      rotate: 45, // 文字旋转 45 度，避免横向挤压
      margin: 10 // 标签与轴线的间距
    }
  },
  yAxis: {},
  series: [
    {
      name: '合格人数',
      type: 'bar',
      data: []
    },
    {
      name: '不合格人数',
      type: 'bar',
      data: []
    },
    {
      name: '专业总人数',
      type: 'bar',
      data: []
    },
  ]
}

onMounted(() => {
  // 加载柱状图数据
  loadBarData();
  // 加载折线图数据
  loadLineData();
  // 加载饼图数据
  loadPieData();
  // 加载柱状图数据
  loadBar2Data();

  // 窗口Resize时调整图表
  window.addEventListener('resize', () => {
    Object.values(data.chartInstances).forEach(chart => chart.resize());
  });
});

// 加载柱状数据
const loadBarData = () => {
  const myChart = echarts.init(document.getElementById('bar'));
  data.chartInstances.bar = myChart;

  alovaInstance.Get('/collegeAdminData/barDataStuCount', {
    params: {collegeId: data.user.collegeId}
  }).then(res => {
    if (res.code === '200') {
      // 检查数据是否存在
      const hasData = res.data.studentCountList && res.data.studentCountList.length > 0;
      data.hasBarData = hasData;

      if (hasData) {
        barOption.xAxis.data = res.data.specialityNames;
        barOption.series[0].data = res.data.studentCountList;
        barOption.series[1].data = res.data.studentCountList;
        myChart.setOption(barOption);
      }
    } else {
      ElMessage.error(res.message || '获取数据失败');
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
  });
};

// 加载折线图数据
const loadLineData = () => {
  const myChart = echarts.init(document.getElementById('line'));
  data.chartInstances.line = myChart;

  alovaInstance.Get('/collegeAdminData/lineDataUserCount', {
    params: {collegeId: data.user.collegeId}
  }).then(res => {
    if (res.code === '200') {
      const hasData = res.data.countList && res.data.countList.length > 0 && res.data.countList.some(item => item > 0);
      data.hasLineData = hasData;

      if (hasData) {
        lineOption.xAxis.data = res.data.dateStrList;
        lineOption.series[0].data = res.data.countList;
        myChart.setOption(lineOption);
      }
    } else {
      ElMessage.error(res.message || '获取数据失败');
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
  });
};

// 加载饼图数据
const loadPieData = () => {
  const myChart = echarts.init(document.getElementById('pie'));
  data.chartInstances.pie = myChart;

  alovaInstance.Get('/collegeAdminData/pieDataStuApplyRecord', {
    params: { collegeId: data.user.collegeId }
  }).then(res => {
    if (res.code === '200') {
      // 从响应中获取数据和数据有效性标识
      const hasData = res.data.hasData;
      const pieData = res.data.data || []; // 从data字段获取数据，默认空数组防止报错

      data.hasPieData = hasData;

      if (hasData) {
        pieOption.series[0].data = pieData;
        myChart.setOption(pieOption);
      }
    } else {
      ElMessage.error(res.message || '获取数据失败');
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
  });
};


// 加载柱状图数据
const loadBar2Data = () => {
  const myChart = echarts.init(document.getElementById('bar2'));
  data.chartInstances.bar2 = myChart;

  alovaInstance.Get('/collegeAdminData/barDataStuScoreCount', {
    params: {collegeId: data.user.collegeId}
  }).then(res => {
    if (res.code === '200') {
      const hasData = res.data.studentCountList && res.data.studentCountList.length > 0;
      data.hasBar2Data = hasData;

      if (hasData) {
        barOption4.xAxis.data = res.data.specialityNames;
        barOption4.series[0].data = res.data.stuScoreSuccessCountList;
        barOption4.series[1].data = res.data.stuScoreErrorCountList;
        barOption4.series[2].data = res.data.studentCountList;
        myChart.setOption(barOption4);
      }
    } else {
      ElMessage.error(res.message || '获取数据失败');
    }
  }).catch(error => {
    console.error('请求失败:', error);
    ElMessage.error(error.message);
  });
};

onUnmounted(() => {
  window.removeEventListener('resize', () => {
    Object.values(data.chartInstances).forEach(chart => chart.resize());
  });
  // 销毁图表实例，释放资源
  Object.values(data.chartInstances).forEach(chart => chart.dispose());
});

</script>

<style scoped>
/* 新增卡片容器样式 */
.card-container {
  position: relative;
  flex: 1;
}

/* 修改后的无数据提示样式 */
.no-data-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(245, 247, 250, 0.9);
  z-index: 10;
  transition: opacity 0.3s ease;
}

.no-data-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #6c757d;
}

.no-data-overlay h3 {
  font-size: 18px;
  margin-bottom: 8px;
  color: #495057;
  font-weight: 500;
}

.no-data-overlay p {
  font-size: 13px;
  max-width: 80%;
  text-align: center;
  color: #6c757d;
  line-height: 1.5;
}
</style>